package crew.gwt.client.widgets.util;

import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.TextBox;

public class NumberBox extends TextBox implements BlurHandler {

	public NumberBox() {
		addBlurHandler(this);
	}

	@Override
	public void onBlur(BlurEvent e) {
		e.stopPropagation();
		try{
			if(getText().isEmpty()) setText("0");
			Integer value = Integer.valueOf(getText());
			if(value < 0){
				setText("0");
				throw new NumberFormatException("Must be a positive integer");
			}
		}catch(NumberFormatException ex){
			Window.alert("Veuillez saisir uniquement des chiffres positifs");
			setFocus(true);
			addStyleName("Form-Element-Wrong");
//			setSelectionRange(0, getText().length());
		}
	}
	
	public Integer getInteger(){
		try{
			Integer ret = Integer.valueOf(getText());
			return ret;
		}catch(NumberFormatException ex){
			return null;
		}
	}
	
	public void setInteger(Integer value){
		setText((value==null) ? "" : value.toString());
	}
}
